import { Component, EventKeyboard, input, Input, KeyCode, _decorator } from 'cc';
import { DirectionInputEvent } from '../Core/Event/DirectionInputEvent';
import EventManager from '../Core/Event/EventManager';
const { ccclass, property } = _decorator;

@ccclass('InputManager')
export class InputManager extends Component {
    direction = {
        up: false,
        down: false,
        left: false,
        right: false
    }
    onLoad() {
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
    }

    onDestroy() {
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.off(Input.EventType.KEY_UP, this.onKeyUp, this);
    }

    onKeyDown(event: EventKeyboard) {
        switch (event.keyCode) {
            case KeyCode.KEY_A:
                this.direction.left = true;
                break;
            case KeyCode.KEY_D:
                this.direction.right = true;
                break;
            case KeyCode.KEY_W:
                this.direction.up = true;
                break;
            case KeyCode.KEY_S:
                this.direction.down = true;
                break;
        }
    }

    onKeyUp(event: EventKeyboard) {
        switch (event.keyCode) {
            case KeyCode.KEY_A:
                this.direction.left = false;
                break;
            case KeyCode.KEY_D:
                this.direction.right = false;
                break;
            case KeyCode.KEY_W:
                this.direction.up = false;
                break;
            case KeyCode.KEY_S:
                this.direction.down = false;
                break;
        }
    }

    update(deltaTime: number) {
        if (this.direction.up) {
            EventManager.getInstance().emit(DirectionInputEvent.UpInput);
        }
        if (this.direction.down) {
            EventManager.getInstance().emit(DirectionInputEvent.DownInput);
        }
        if (this.direction.left) {
            EventManager.getInstance().emit(DirectionInputEvent.LeftInput);
        }
        if (this.direction.right) {
            EventManager.getInstance().emit(DirectionInputEvent.RightInput);
        }
    }
}


